package cn.stylefeng.guns.modular.business.util;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAEncrypt {
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥

    public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI3xFTAYiHECVuH9JQCxm7un8Ma/uroiZhgzkuaktUC7a4uxzgj+5b1mgduUBsDTBNXqyP/wRI1cw6S7kWRtK0bDKC9/d+txwsI+ks8RftYSJjrfDCmg33NJ+ywsoPIIJ0Nv9Su+XqJ91mUvFIZ3WvSRPMaFxIsg3WZ48/9WRPP5AgMBAAECgYBC+dsRksHu8Tel8xketq/RYHFQlu+5HLon+U373wRXwxgAFqotvHkTYecsgTCek/PYLK0jd3AhdAAtHwR/6rNcQANfhfafvGLAvNOvrzka1ABsGN+TxOOBPu1uMM+XJ4MCKOUyt6hHlsLBBa8ZIhapf5h7PMFOwLkZ0qx/aGQqcQJBAM7UzPsnez+woPYO3q7FOURL41aqZhFYmuYUAuYtO06Xl81CzmWB8I6S+PHZEwiHcFkqXcHS4Hg1OEtuPeuENmcCQQCvr0dJWsFuWYvg/8/pD0sJsfFVfT4kixDtiIwAPJ0Aza2XC86ne1COUij7b1D8MG+rhadW7hguZ0HIaG7TIUafAkEAs6ll5USGauyi5RpFlMr807aX49BgmPC+nN0FJ6xiuAI2erZtUv9sVmyUkoBdaCs+DDYg+xySn9ia7er1Hn/aQQJAcJ2w2oq8l5n7Gl2gzsqo1SwlgSFpZk9mqHzxEW3JTqyJa9t7usxHVRPBhXtTtHTwAEkKfaTeB1DVUDvxXpFkDQJADkaxyVKTS3sPWmfaSbEOT5ileFYfovUyq/fXhDch9zh09+eCv9GUNaels+Knt7GsDAb0Rb58l+gn7pNDDRmLig==";
    public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCN8RUwGIhxAlbh/SUAsZu7p/DGv7q6ImYYM5LmpLVAu2uLsc4I/uW9ZoHblAbA0wTV6sj/8ESNXMOku5FkbStGwygvf3frccLCPpLPEX7WEiY63wwpoN9zSfssLKDyCCdDb/Urvl6ifdZlLxSGd1r0kTzGhcSLIN1mePP/VkTz+QIDAQAB";
//    public static  String privateKey ="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCsMPR0bLBPWgcC" +
//            "U7vwdY2jT7RQmJy2jfRShFDNsQwyGmIFkquQX/veuGdfsyMafmITcSo2zwLbiAJv" +
//            "aY5bf0WBWpoqawWwotswCP7AwPqOSG1mon7m/H5ShTYgQG0h+6Phh5HyAV3OR4lV" +
//            "XieWs5PZKI576FuEB3iugHiM9jlvvTgt+l5YG+5mtArvCh7Argci6Yyv491Zb36q" +
//            "SIFg4jCsjYg267YZECbOZJpLPoxdf7oiEMTqkdRGHwwTiBh1Xtxo6K5IYCSccHes" +
//            "hg1PlgwPAhlOwhcXinWRWwzXUyRFLf0Jr/i6KEAOjHcKDu2EXrgNWKGOh4UDOLmr" +
//            "JrzM3P1fAgMBAAECggEAZ3zUrtRT8p0M8V0Z6x77jVdt67KNHTqbyKw1VCpARiyN" +
//            "FQRdkFvfqK/zkRS82EN09nJhCKfJ897+d69dG6iWQXQOi8fel5aJXYlKctaIv9LP" +
//            "zYuD8Zd25GmjaibOcEoo6HbuRCCGHF/qLiB0cqJjDXTOjbHMrsE+ysHzseSaCIkY" +
//            "OnEFvdp9GBKi+0KQj6ZtxaWZqgr/HwGX3mbpRg5Cs0WYrtuxS8W34BGfDFpI5wK9" +
//            "FDzYd+JFzLzgv1H9R1eJyWpV0TM0F7XwvElK6cm75rCfYkHWYlD+QqOyJzOl7yN2" +
//            "lhR0kbv3bZhB8TGGQphrzF8CwTz8UEIgRArc267foQKBgQDWP5jKGdV5r0Oi4OFc" +
//            "ZqkYmUcffLhKQAZN3+ktS88j3McJc56FY88qEk3rgwQJv0fiNm6u9qabu12PbKg/" +
//            "bNSu0AWu4q4c+tf4JX6MnfztpbuBdHPGdJlmY0M8mH7YaTckFgFtyidJpqjyl1mG" +
//            "c3pZTn+IfMrgmC1YgRIRYC1mywKBgQDNvzaNNIZJiyqpHYozMYwcZa8DksJ77BeX" +
//            "RhPikd3hNBKkljFlzIc8SaL/mKuDrO9pv6HmMK8NFIbM4TITJ9ycFN6H8MbfIj7U" +
//            "NrWCzjerDm+n+okDhq+lKd5hFg2WiF9SP1du2H+QaAv5EItkzaugnmJzJmF759Fg" +
//            "CEoQLOOdPQKBgAGV5OaR/F9zKZf5/BD3/YZeFAWqoZ6DDMjkwFACgJzuVFbAkUrB" +
//            "a1YPXp5AkPYVgU2uQ3FuB9udLlsSXchiYMyOY4xgxxMV1CVU+bPGs4l6sYGKwBSW" +
//            "5k+4qlW3dzDYznyo4QfT+Ch2YEezUQlKr3wbtZvn+IRi++rswZp5ULyzAoGAMjou" +
//            "2BPtgICv3m8usMa0vK36JrYqMlR1geGCszoG35Z1wqZD0uU2Unprh1g+7rtGCxvU" +
//            "KzzRTzEmo1eKgPCnQ5c4qBkYg5p5mhbtAszS/Dhe+7QGxMyZjomFF1Bp6sjJ9Gsw" +
//            "Lgg+RAOSgLAQR4CKGIDx6ciB3dy+2WHMqtw6iMUCgYBS102VHAkJ/1fZKW0ZLvo4" +
//            "DW6eRQ75XMZHGS08Vz10O4LN7udPOHYQG6KnHMLU3baa0180og7YFnr+2rOe7LnU" +
//            "p8fxADPPuPIIjo4d5+Y9+7oSIPfmoRXq/mLNeWadLO05BP7ad0YbYVd79stmCQyk" +
//            "UGtgwo8eBvhgrg6k8bycCA==";
//public static  String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCCViKycwG6xUhLsKfdvmHpATOQSA6cMV159B1Qwq8cnbEwJSdbvVeLm3Rr5QUXy2WrWc4baPVa3Ruvl5y7T9ej96JBG5qhlU730LHZRr3DqAt6uUTVGepDYpF6+bGhjoOm9VFBXf9XZt8ceKU9ahY+/bw48b9491IdS++q9+c5wIDAQAB";

//    public static void main(String[] args) throws Exception {
//        String phone = "18256057064";
//        String encrypt = encrypt(phone, publicKey);
//        System.out.println("加密后"+encrypt);
//        System.out.println("解密后"+decrypt(encrypt, privateKey));
//    }

    public static void main(String[] args) throws Exception {
        genKeyPair();
        System.out.println(keyMap.get(0));
        System.out.println(keyMap.get(1));
    }

    /**
     * 随机生成密钥对
     *
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put(0, publicKeyString);  //0表示公钥
        keyMap.put(1, privateKeyString);  //1表示私钥

        System.out.println("公钥:" + publicKeyString);
        System.out.println("私钥:" + privateKeyString);
    }

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }


}